$(function () {

  history();

  $('#moviesName').on('focus', function () {
    $("#search").slideDown();
    history();
  })

  $('#moviesName').on('blur', function () {
    $("#search").slideUp();
  })

  //将历史记录或者推荐的电影显示到文本框内
  $('#recommend').on('click', 'li', function () {
    $('#moviesName').val($(this).text())
  })

  $('#history').on('click', 'li', function () {
    $('#moviesName').val($(this).text())
  })

  //清空历史记录
  $('#removeHistory').on('click', function () {
    localStorage.removeItem(('history'));
    $('#history ul').children().remove();
    $("#search").slideUp();
  })

  // 搜索历史
  $('#find').on('click', function () {
    var name = $('#moviesName').val();
    var history = localStorage.getItem('history');
    $.ajax({
      url: 'https://www.fastmock.site/mock/bb4157f45a0b5ffdcb3f6d984517a6c0/woniuMovie/getAllMovies',
      success(data) {
        let movies = data.movies;
        if (name != "") {

          if (history != null) {
            var newhistory = history.split(",");
            newhistory = newhistory.filter(function (v) {
              return v != name
            })
            if (newhistory != "") {
              localStorage.setItem('history', `${newhistory},${name}`);
            } else {
              localStorage.setItem('history', name);
            }
            $('#moviesName').val("");
            var movie = movies.filter(function (v, i) {
              if (v.title == name) {
                return v;
              }
            })
            if (movie != "") {
              $("#search").slideUp();
              location.href = `details.html?id=${movies[0].id}`
            } else {
              alert('未找到相关影片');
            }
          } else {
            localStorage.setItem('history', name);
            $('#moviesName').val("");
            var movie = movies.filter(function (v, i) {
              if (v.title == name) {
                return v;
              }
            })
            if (movie != "") {
              $("#search").slideUp();
              location.href = `details.html?id=${movies[0].id}`
            } else {
              alert('未找到相关影片');
            }
          }
        } else {
          alert('请输入电影名称')
        }
      }
    });
  })
});
//显示搜索历史
function history() {
  var history = localStorage.getItem('history');
  $('#history ul').children().remove();
  if (history != null) {
    $('#recommend').css('display', "none");
    $('#history').css('display', "block");
    history = history.split(",");
    history.forEach(function (v, i) {
      var newul = $("<li></li>")
      newul.text(`${v}`);
      $('#history ul').append(newul);
    })
  } else {
    $('#recommend').css('display', "block");
    $('#history').css('display', "none");
  }
}